<template>
	<a-image width="140" height="60" :src="$index.imgUrl+'logo.png'" style="transform: translateX(75%);"
		draggable="false" :preview="false" />
	<a-row id="topbar-leftnav" justify="space-between" align="center">
		<a-col :span="4">
			<a draggable="false" href="#">{{$t('topbarLeftnav.forum')}}</a>
		</a-col>
		<a-col :span="5">
			<a draggable="false" href="#">{{$t('topbarLeftnav.data')}}</a>
		</a-col>
		<a-col :span="5">
			<a draggable="false" href="#">{{$t('topbarLeftnav.event')}}</a>
		</a-col>
		<a-col :span="5">
			<a draggable="false" href="#">{{$t('topbarLeftnav.applet')}}</a>
		</a-col>
		<a-col :span="5">
			<a draggable="false" href="#">{{$t('topbarLeftnav.focus')}}</a>
		</a-col>
	</a-row>
	<a-row id="topbar-rightnav" justify="space-between" align="center" >
		<a-space class="icon" :size="18" style="padding-left: 2%;">
			<div id="topbar-rightnav-search" v-if="isSearchPage == false">
				<a-auto-complete :data="formathotList.hotList" :model-value="keyword"
					style="width: 220px;border-radius: 25px;border: 1px solid lightgray;"
					:placeholder="$t('topbarLeftnav.placeholder')" @search="handleSearch" @select="handleSelect">
					<template #suffix>
						<icon-search class="icon black" style="cursor: pointer;" @click="searchbyKeyword(keyword)" />
					</template>
				</a-auto-complete>
			</div>
			<div id="topbar-rightnav-search" v-else-if="isSearchPage == true" style="visibility: hidden;">
				<a-auto-complete :data="formathotList.hotList" :model-value="keyword"
					style="width: 220px;border-radius: 25px;border: 1px solid lightgray;"
					:placeholder="$t('topbarLeftnav.placeholder')" @search="handleSearch" @select="handleSelect">
					<template #suffix>
						<icon-search class="icon black" style="cursor: pointer;" @click="searchbyKeyword(keyword)" />
					</template>
				</a-auto-complete>
			</div>
			<icon-translate class="icon blue" style="width: 20px;height: 20px;cursor: pointer;"
				@click="changeLanguage" />
			<icon-font-colors class="icon blue" style="width: 20px;height: 20px;cursor: pointer;"
				@click="changeThemeColor" />
			<!--登录按钮-->
			<a-button type="primary" style="width: 88.3px;text-align: center;" @click="loginVisible" v-if="!loginStatus">
				<template #icon>
					<icon-user />
				</template>
				<template #default>{{$t('topbarLeftnav.login')}}</template>
			</a-button>
			<!--注册按钮-->
			<a-button type="primary" style="width: 106.3px;text-align: center;" @click="registerVisible" v-if="!loginStatus">
				<template #icon>
					<icon-user-add />
				</template>
				<template #default>{{$t('topbarLeftnav.register')}}</template>
			</a-button>
			<!--登录后显示头像-->
			<a-popover>
				<a-avatar v-if="userInfo.data && loginStatus" @click="toUser">
					<img alt="avatar"
						:src="userInfo.data.avatar" />
				</a-avatar>
				<a-avatar v-else v-show="loginStatus == true" style="background-color: var(--color-fill-4);">&nbsp;</a-avatar>
				<template #content>
					<a-card style="width: 300px;text-align: center;height: 250px;" hoverable>
						<a-space :size="5" direction="vertical" fill>
							<a-avatar :size="60">
								<img alt="avatar"
									:src="userInfo.data.avatar" />
							</a-avatar>
							<a-typography-paragraph style="font-size: 25px;font-weight: bold;" ellipsis>
								{{userInfo.data.nickName}}
							</a-typography-paragraph>
							<a-descriptions :data="[{label: '关注',value: userInfo.data.focus},
							{label: '文章',value: userInfo.data.article}, {label: '点赞',value: userInfo.data.good}]" layout="inline-vertical" style="margin-left: 20%;" />
							<a-button type="primary" style="width: 88.3px;text-align: center;" @click="loginOut">
								退出登录
							</a-button>
						</a-space>
					</a-card>
				</template>
			</a-popover>
			<!--购物车-->
			<shoppingCart v-if="loginStatus">
			</shoppingCart>

			<!--登录表单-->
			<loginFormList :formVisible="loginformVisible" @getloginFormVisible="getloginData" :loginForm="loginForm"
			@getLoginStatus="isLogin">
			</loginFormList>
			<!--注册表单-->
			<registerFormList :formVisible="registerformVisible" @getregisterFormVisible="getregisterData"
				:registerForm="registerForm">
			</registerFormList>
		</a-space>
	</a-row>
</template>

<script setup>
	import {
		ref,
		reactive,
		getCurrentInstance,
		onMounted,
		provide,
		watch,
		nextTick
	} from 'vue';

	//国际化组件
	import enUS from '@arco-design/web-vue/es/locale/lang/en-us';
	import zhCN from '@arco-design/web-vue/es/locale/lang/zh-cn';

	import recommendList from '@/components/index/recommendList.vue';
	import newProductList from '@/components/index/newProductList.vue';
	import hotCommentList from '@/components/index/hotCommentList.vue';
	import loginFormList from '@/components/index/loginForm.vue';
	import registerFormList from '@/components/index/registerForm.vue';
	import topBar from '@/components/index/topBar.vue';
	import shoppingCart from '@/components/index/shoppingCart.vue';

	import indexApi from '@/module/index/api/index.js';
	import jwt_decode from 'jwt-decode';

	import {
		useRouter
	} from 'vue-router';
	import {
		useRoute
	} from 'vue-router';
	let router = useRouter();
	let route = useRoute();

	const props = defineProps({
		formVisible: Boolean,
		loginForm: Object,
		isSearchPage:Boolean,
		refrushAvatar:Boolean
	});

	const emit = defineEmits(['loginVisibleShow', 'registerVisibleShow','getLoginUserInfo','getRefrushUserInfo']);

	let {
		proxy
	} = getCurrentInstance();

	let language = ref(zhCN);

	let hotList = reactive({});
	let formathotList = reactive({});

	let keyword = ref('');

	let loginformVisible = ref(false);
	let loginForm = reactive({
		userName: '',
		passWord: '',
		verify: ''
	});
	let registerformVisible = ref(false);
	let registerForm = reactive({
		userName: '',
		passWord: '',
		rePassword: '',
		telePhone: '',
		nickName: '',
		verify: ''
	});
	
	let loginStatus = ref();
	let loginMessage = reactive({});
	let userInfo = reactive({});
	
	async function loadingUserInfo(){
		if(sessionStorage.getItem("token")){
			userInfo.detail = jwt_decode(sessionStorage.getItem("token"));
			console.log('userInfo',userInfo.detail.uid);
			if(userInfo.detail.uid != undefined || userInfo.detail.uid != null || userInfo.detail.uid != ''){
				loginStatus.value = true;
			}
			userInfo.resp = await indexApi.getUserInfo(userInfo.detail.uid);
			userInfo.data = userInfo.resp.data;
			console.log('userInfo',userInfo.data);
			emit('getLoginUserInfo',userInfo.data);
		}
	}
	
	watch(()=>props.refrushAvatar,(NewValue,PreValue)=>{
		if(NewValue != PreValue){
			loadingUserInfo();
			emit('getRefrushUserInfo',userInfo.data);
		}
	});
	
	async function loginOut(){
		loginStatus.value = false;
		loginMessage.data = await indexApi.logOut();
		if(loginMessage.data.message == '退出登录成功'){
			sessionStorage.removeItem("token");
			console.log('loginMessage',loginMessage.data);
			//判断当前页面是否有权限查看
			console.log('path',route.fullPath);
			console.log('status',route.meta.status);
			if(route.fullPath.indexOf('modelEvaluating') >= 0 || route.fullPath.indexOf('index') >= 0 || 
			   route.fullPath.indexOf('search') >= 0){
			   proxy.$message.success('注销成功');
			}
			else{
				router.push({
					name: 'index',
					params: {
						status: '注销成功'
					}
				})
			}
			indexApi.deleteUserToken(userInfo.detail.uid);
		}
	}
	
	function isLogin(item){
		loginStatus.value = item.flag;
		if(loginStatus.value == true)
			loadingUserInfo();
	}
	
	function isLoginStatus(){
		if(sessionStorage.getItem("token")){
			loginStatus.value = true;
		}else{
			loginStatus.value = false;
		}
	}

	function handleSearch(value) {
		if (value) {
			keyword.value = value.substring((value.indexOf('-') + 1), value.length);;
			console.log("输入时触发",keyword.value);
		} else {
			keyword.value = '';
		}
	}
	//选择下拉列表时触发
	function handleSelect(item) {
		if (item) {
			keyword.value = item.substring((item.indexOf('-') + 1), item.length);
			console.log("选择下拉选项时触发",keyword.value);
		} else {
			keyword.value = '';
		}
	}

	function searchbyKeyword(value) {
		if (value) {
			keyword.value = value.substring((value.indexOf('-') + 1), value.length);;
			console.log("点击搜索按钮时触发",keyword.value);
			router.push({path: '/search',query:{keyword: keyword.value}});
		} else {
			if(keyword.value == ''){
				proxy.$message.warning('请输入感兴趣的内容!');
			}
			else if(keyword.value == undefined || keyword.value == null){
				proxy.$message.warning('搜索出现错误!');
			}
		}
	}

	function changeLanguage() {
		console.log('当前语言', language.value);
		if(localStorage.getItem('language') == undefined){
			localStorage.setItem('language','en');
			language.value = enUS;
						
			proxy.$i18n.locale = localStorage.getItem('language');
		}
		else{
			nextTick(()=>{
				loadingLanguage();
			})
			if(localStorage.getItem('language') == 'en'){
				localStorage.setItem('language','zh');
			}
			else if(localStorage.getItem('language') == 'zh'){
				localStorage.setItem('language','en');
			}
		}
	}
	
	function loadingLanguage(){
		if(localStorage.getItem('language') == 'en'){
			language.value = enUS;
						
			proxy.$i18n.locale = localStorage.getItem('language');
			console.log('切换后语言', language.value);
		}
		else if(localStorage.getItem('language') == 'zh'){
			language.value = zhCN;
						
			proxy.$i18n.locale = localStorage.getItem('language');
			console.log('切换后语言', language.value);
		}
	}

	function changeThemeColor() {
		if(localStorage.getItem('arco-theme') == undefined){
			localStorage.setItem('arco-theme','dark');
			document.body.setAttribute('arco-theme', localStorage.getItem('arco-theme'));
			document.documentElement.style.setProperty('--color-content', '#4c4c4c');
			document.documentElement.style.setProperty('--color-content-a', '#f4f4f4');
			document.documentElement.style.setProperty('--color-font', '#f4f4f4');
			if(document.getElementById('content') != undefined){
				document.getElementById('content').style.setProperty('--color-content', '#4c4c4c');
			}
		}
		else{
			nextTick(()=>{
				loadingThemeColor();
			});
			if(localStorage.getItem('arco-theme') == 'dark'){
				localStorage.setItem('arco-theme','white');
			}
			else if(localStorage.getItem('arco-theme') == 'white'){
				localStorage.setItem('arco-theme','dark');
			}
		}
	}
	
	function loadingThemeColor(){
		if(localStorage.getItem('arco-theme') == 'dark'){
			document.body.setAttribute('arco-theme', localStorage.getItem('arco-theme'));
			document.documentElement.style.setProperty('--color-content', '#4c4c4c');
			document.documentElement.style.setProperty('--color-content-a', '#f4f4f4');
			document.documentElement.style.setProperty('--color-font', '#f4f4f4');
			if(document.getElementById('content') != undefined){
				document.getElementById('content').style.setProperty('--color-content', '#4c4c4c');
			}
		}
		else if(localStorage.getItem('arco-theme') == 'white'){
			document.body.removeAttribute('arco-theme');
			document.documentElement.style.setProperty('--color-content', '#f4f4f4');
			document.documentElement.style.setProperty('--color-content-a', '#4c4c4c');
			document.documentElement.style.setProperty('--color-font', '#4c4c4c');
			if(document.getElementById('content') != undefined){
				document.getElementById('content').style.setProperty('--color-content', '#f4f4f4');
			}
		}
	}

	function getloginData(data) {
		loginformVisible.value = data;
		console.log('loginVisable', data);
		emit('loginVisibleShow', loginformVisible.value);
	}

	function getregisterData(data) {
		registerformVisible.value = data;
		console.log('registerVisable', data);
		emit('registerVisibleShow', registerformVisible.value);
	}

	function loginVisible() {
		loginformVisible.value = true;
		emit('loginVisibleShow', loginformVisible.value);
	}

	function registerVisible() {
		registerformVisible.value = true;
		emit('registerVisibleShow', registerformVisible.value);
	}

	function formatHotList() {
		formathotList.hotList = hotList.resp.data.map((item, index) => {
			return formathotList[index] = `${index+1}-${item}`;
		});
		console.log('formathotList:', formathotList.hotList);
	}

	async function loadingHotList() {
		hotList.resp = await indexApi.getHotList();
		formatHotList();
		console.log('hotList', hotList.resp);
		return hotList;
	}

	function toUser() {
		console.log('fullPath:', route.fullPath);
		if (route.fullPath.indexOf('/user')) {
			router.push({
				name: 'user'
			});
		} else {
			proxy.$message.warning('当前已经是个人中心页面了哦!');
		}
	}
	
	onMounted(() => {
		document.documentElement.style.setProperty('--color-content', '#f4f4f4');
		document.documentElement.style.setProperty('--color-font', 'gray');
		loadingHotList();
		loadingUserInfo();
		loadingLanguage();
		loadingThemeColor();
		window.addEventListener('unload',(e) => {
			indexApi.deleteUserToken(userInfo.detail.uid);
			//navigator.sendBeacon("http://localhost:9232/sso/delete/user/token/" + userInfo.detail.uid)
		},false)
		console.log('env',
			import.meta.env);
	});
</script>

<style lang="less" scoped>
	@import '@/assets/index/css/topbar.less';
</style>
